package com.zeh.bill.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zeh.bill.entity.Dto.RolePermissionDTO;
import com.zeh.bill.entity.Permission;
import com.zeh.bill.entity.Role;
import com.zeh.bill.entity.Vo.RolePermissionVo;
import com.zeh.bill.entity.Vo.RoleQueryVo;
import com.zeh.bill.service.PermissionService;
import com.zeh.bill.service.RoleService;
import com.zeh.bill.untils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zeh
 * @since 2022-07-18
 */
@RestController
@RequestMapping("/api/role")
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    /**
     * 分页查询角色列表
     */
    @GetMapping("/list")
    public Result list(RoleQueryVo roleQueryVo){
        Page<Role> page = new Page<>(roleQueryVo.getPageNo(), roleQueryVo.getPageSize());
        roleService.findRoleListByUserId(page,roleQueryVo);
        return Result.ok(page);
    }


    /**
     * 添加角色
     */
    @PostMapping("/add")
    public Result add(@RequestBody Role role){
        if(roleService.save(role)){
            return Result.ok().message("角色添加成功");
        }
        return Result.error().message("角色添加失败");
    }


    /**
     * 修改角色
     */
    @PutMapping("/update")
    public Result  update(@RequestBody Role role){
        if(roleService.updateById(role)){
            return Result.ok().message("角色修改成功");
        }
        return Result.error().message("角色修改失败");
    }

    /**
     * 删除角色
     */
    @DeleteMapping("/delete/{id}")
    public Result  delete(@PathVariable  Long id){
        if(roleService.removeById(id)){
            return Result.ok().message("角色删除成功");
        }
        return Result.error().message("角色删除失败");
    }

    /**
     * 分配权限-查询权限树数据
     *
     */
     @GetMapping("/getAssignPermissionTree")
    public Result getAssignPermissionTree(Long userId,Long roleId){
         RolePermissionVo permissionTree = permissionService.findPermissionTree(userId, roleId);
         return Result.ok(permissionTree);
     }

    /**
     * 分配权限-保存权限数据
     * @param rolePermissionDTO
     * @return
     */
    @PostMapping("/saveRoleAssign")
    public Result saveRoleAssign(@RequestBody RolePermissionDTO rolePermissionDTO){
           if(roleService.saveRolePermission(rolePermissionDTO.getRoleId(),rolePermissionDTO.getList())){
               return Result.ok().message("权限分配成功");
           }else{
               return Result.error().message("权限分配失败");
           }

    }



}

